import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'


const LogIn = () => import(/* webpackChunkName: "login" */ '@/views/LogIn')
const Home = () => import(/* webpackChunkName: "home" */ '@/views/Home')
const Users = () => import(/* webpackChunkName: "users" */'@/views/users/Users')
const Roles = () => import(/* webpackChunkName: "rights" */'@/views/rights/Roles')
const NotFound = () => import('@/views/NotFound')
const Goods = () => import('@/views/goods/Goods')
const AddGoods = () => import('@/views/goods/AddGoods')
const Rights = () => import(/* webpackChunkName: "rights" */'@/views/rights/Rights')
const Params = () => import('@/views/goods/Params')
const Reports = () => import('@/views/reports/Reports')

// import LogIn from '@/views/LogIn'
// import Home from '@/views/Home'
// import Users from '@/views/users/Users'
// import Roles from '@/views/rights/Roles'
// import NotFound from '@/views/NotFound'
// import Goods from '@/views/goods/Goods'
// import AddGoods from '@/views/goods/AddGoods'
// import Rights from '@/views/rights/Rights'
// import Params from '@/views/goods/Params'

const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(Router)

const routes = new Router({
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'login',
      component: LogIn,
      meta: { requiresAuth: true }
    },
    {
      path: '/home',
      name: 'home',
      component: Home,
      children: [
        {
          path: 'users',
          name: 'users',
          component: Users
        },
        {
          path: 'roles',
          name: 'roles',
          component: Roles
        },{
          path: 'goods',
          name: 'goods',
          component: Goods
        },{
          path: 'goodsadd',
          name: 'goodsadd',
          component: AddGoods
        },{
          path: 'rights',
          name: 'rights',
          component: Rights
        },{
          path: 'params',
          name: 'params',
          component: Params
        },{
          path: 'reports',
          name: 'reports',
          component: Reports
        }
      ]
    },
    {
      path: '*',
      name: '404',
      component: NotFound
    }
  ],
  linkActiveClass: 'actived-class'
})

routes.beforeEach((to, from, next) => {
  if(!to.meta.requiresAuth) {
    if(store.state.token){
      next()
    }else {
      next({
        path: '/login'
      })
    }
  }else {
    next()
  }
})

export default routes